package com.caiyi.financial.nirvana.sms.service;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.enums.ReturnCodeEnum;
import com.caiyi.financial.nirvana.sms.enums.SmsAuditBatchStatusEnum;
import com.caiyi.financial.nirvana.sms.filters.*;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.param.SendMsgParam;
import com.caiyi.financial.nirvana.sms.queue.SendQueueEntity;
import com.caiyi.financial.nirvana.sms.util.CommUtil;
import com.caiyi.financial.nirvana.sms.util.CoreSendUtil;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class SmsMsgSendService {

    public String sendMsg(SendMsgParam param, HttpServletRequest request) {
        //过滤链
        FilterChain chain = new FilterChain(param);
        chain.setIp(CommUtil.getClientIp(request));
        chain.addFilter(new ParamsFilter());
        chain.addFilter(new AccountFilter());
        chain.addFilter(new TemplateFilter());
        chain.addFilter(new ContentFilter());
        chain.addFilter(new KeywordFilter());
        chain.addFilter(new BalanceFilter());
        chain.doFilter();

        //通过验证 入队操作
        SendQueueEntity entity = new SendQueueEntity();
        entity.setIp(chain.getIp());
        entity.setNotifyUrl(param.getNotifyUrl());
        entity.setUid(param.getUid());
        entity.setAccount(param.getAccount());
        entity.setContent(param.getContent());
        entity.setPhone(param.getPhones());
        entity.setPhoneCount(chain.getPhones().size());
        entity.setProductId(chain.getSmsUser().getProductId());
        entity.setAccessNumber(param.getExtend());
        String batchId = CommUtil.generateBatchId();
        entity.setBatchId(batchId);

        //模板未匹配上，入库审核表,状态为审核中
        if (ReturnCodeEnum.TEMPLATE_ERROR.code.equals(chain.getTemplateCode())) {
            entity.setStatus(SmsAuditBatchStatusEnum.AUDIT.index);
            entity.setPhone(chain.getPhones().toString().replace(" ", "").replace("[", "").replace("]", ""));
            //batch_audit表入库队列
            JedisService.lpush(JedisKey.SMS_QUEUE_BATCH_MSG_AUDIT_DB, JSON.toJSONString(entity));
            return batchId;
        }

        //短信发送
        CoreSendUtil.handlerBusiness(chain.getPhones(), entity, chain.getSmsUser());
        return batchId;
    }

}
